package com.example.myapplication.slice;

import com.example.myapplication.ResourceTable;
import com.example.myapplication.beans.CartData;
import com.example.myapplication.provider.IndexImgPageSliderProvider;
import com.example.myapplication.beans.Category;
import com.example.myapplication.provider.CategoryItemProvider;
import com.example.myapplication.provider.TabPageSliderProvider;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.event.notification.NotificationHelper;
import ohos.event.notification.NotificationRequest;
import ohos.event.notification.NotificationSlot;
import ohos.global.resource.NotExistException;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.rpc.RemoteException;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class MainAbilitySlice extends AbilitySlice implements Component.FocusChangedListener{

    private ScheduledExecutorService scheduler;
    private int currentPage = 0;
    private int status = 0; //订单状态
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss");
    private static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00201, "MainAbilitySlice");

    PageSlider indexImgPageSlider;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

            //1.初始化TabList
            TabList tabList = (TabList) findComponentById(ResourceTable.Id_tab_list);
            String[] tabListTags = {"首页","分类","购物车","我的"};
            for (int i = 0; i < tabListTags.length ; i++) {
                TabList.Tab tab = tabList.new Tab(this);
                tab.setText(tabListTags[i]);
                tabList.addTab(tab);
            }

            //2.初始化PageSlider
            List<Integer> layoutFileIds = new ArrayList<>();
            layoutFileIds.add(ResourceTable.Layout_ability_main_index);
            layoutFileIds.add(ResourceTable.Layout_ability_main_category);
            layoutFileIds.add(ResourceTable.Layout_ability_main_shopcart);
            layoutFileIds.add(ResourceTable.Layout_ability_main_user_center);
            PageSlider pageSlider = (PageSlider) findComponentById(ResourceTable.Id_page_slider);
            pageSlider.setProvider( new TabPageSliderProvider(layoutFileIds,this));

            //3.TabList与PageSlider联动
            tabList.addTabSelectedListener(new TabList.TabSelectedListener() {
                public void onSelected(TabList.Tab tab) {
                    //获取点击的菜单的索引
                    int index = tab.getPosition();
                    //设置pageSlider的索引与菜单索引一只
                    pageSlider.setCurrentPage(index);
                    if(index==0){
                        //首页
                        initIndex(pageSlider);
                    }else if(index ==1){
                        //分类
                        initCategory(pageSlider);
                    }else if(index ==2){
                        //购物车
                        initShopcart(pageSlider);
                    }else if(index ==3){
                        //我的
                        initUserCenter(pageSlider);
                    }
                }
                public void onUnselected(TabList.Tab tab) { }
                public void onReselected(TabList.Tab tab) { }
            });
            pageSlider.addPageChangedListener(new PageSlider.PageChangedListener() {
                public void onPageSliding(int i, float v, int i1) {}
                public void onPageSlideStateChanged(int i) {}
                public void onPageChosen(int i) {
                    //参数i就表单当前pageSlider的索引
                    if (tabList.getSelectedTabIndex() != i){
                        tabList.selectTabAt(i);
                    }
                }
            });

            //4.tabList默认选中第一个菜单，加载PageSlider的第一个页面（默认）
            tabList.selectTabAt(0);

        }



    private void initUserCenter(PageSlider pageSlider) {
        Component layout =
                pageSlider.findComponentById(ResourceTable.Id_layout_product01);
        System.out.println("--------------------------3:"+layout);


        Button btn = (Button) pageSlider.findComponentById(ResourceTable.Id_user_me);
        btn.setClickedListener(component -> {
            Intent intent = new Intent();
            present(new MeAbilitySlice(),intent);
        });
    }

    /**初始化购物车列表*/
    private void initShopcart(PageSlider pageSlider) {
        // 获取购物车数据
        Map<String, Object> cartParams = CartData.getInstance().getCartParams();

        // 使用购物车数据
        String cartNum = (String) cartParams.get("cartNum");
        String productId = (String) cartParams.get("productId");
        String productPrice = (String) cartParams.get("productPrice");

        // 将商品ID显示到商品详情页面的 product_id_text 的文本中
        Text shoptext = (Text) findComponentById(ResourceTable.Id_shopcart_item_product_name_text4);
        if (shoptext != null) {
            shoptext.setText(cartNum);
        } else {
            System.out.println("--------------shoptext is null！");
        }

        Button btn = (Button) pageSlider.findComponentById(ResourceTable.Id_account_button);
        btn.setClickedListener(component -> {
            Intent intent = new Intent();
            present(new OrderAddAbilitySlice(), intent);
        });

    }

    /** 初始化分类信息显示 */
    private void initCategory(PageSlider pageSlider) {
        TextField searchTextField = (TextField) findComponentById(ResourceTable.Id_category_search_textfield);
        searchTextField.setFocusChangedListener(this);
        ListContainer listContainer = (ListContainer) findComponentById(ResourceTable.Id_fisrt_level_category_listcontainer);
        List<Category> data = getCategory();
        CategoryItemProvider categoryItemProvider = new CategoryItemProvider(data,this);
        listContainer.setItemProvider(categoryItemProvider);

        listContainer.setItemClickedListener(new ListContainer.ItemClickedListener() {
            @Override
            public void onItemClicked(ListContainer listContainer, Component component, int i, long l) {
                Category category = (Category) listContainer.getItemProvider().getItem(i);
                new ToastDialog(getContext())
                        .setText("点击了"+category.getName())
                        .setAlignment(LayoutAlignment.CENTER)
                        .show();
            }
        });

    }

    private List<Category> getCategory() {
        List<Category> categories = new ArrayList<>();
        categories.add(new Category("食品系列", ResourceTable.Media_c_icno1));
        categories.add(new Category("宇宙系列", ResourceTable.Media_c_icno2));
        categories.add(new Category("温度系列", ResourceTable.Media_c_icno3));
        categories.add(new Category("奶油系列", ResourceTable.Media_c_icno4));
        categories.add(new Category("漫相集系列", ResourceTable.Media_c_icno5));
        categories.add(new Category("重塑系列", ResourceTable.Media_c_icno6));
        categories.add(new Category("约会日系列", ResourceTable.Media_c_icno7));
        return categories;
    }

    /**
     * 初始化首页
     */
    private void initIndex(PageSlider pageSlider) {

        //渲染数据：通过接⼝从后台获取数据，并显示到 ability_main_index.xml 布局⽂件的组件中
        Component productLayout = pageSlider.findComponentById(ResourceTable.Id_layout_product01);

        productLayout.setClickedListener(component -> {
            //当index==0时，绑定商品列表的点击事件，点击跳转到详情⻚时，将商品id传递过去
            Intent intent = new Intent();
            Text s=(Text) findComponentById(ResourceTable.Id_product_name_text);
            String s1 = s.getText();

            Text a=(Text) findComponentById(ResourceTable.Id_product_price_text1);
            String a1 = a.getText();

            Image b=(Image) findComponentById(ResourceTable.Id_product_image);

            intent.setParam("aproductId",a1);
            intent.setParam("productId",s1);


            this.present(new DetailAbilitySlice(),intent);
        });

        Component productLayout2 = pageSlider.findComponentById(ResourceTable.Id_layout_product02);

        productLayout2.setClickedListener(component -> {
            //当index==0时，绑定商品列表的点击事件，点击跳转到详情⻚时，将商品id传递过去
            Intent intent = new Intent();
            Text s=(Text) findComponentById(ResourceTable.Id_product_name_text2);
            String s1 = s.getText();

            Text a=(Text) findComponentById(ResourceTable.Id_product_price_text2);
            String a1 = a.getText();

            intent.setParam("aproductId",a1);
            intent.setParam("productId",s1);
            this.present(new DetailAbilitySlice2(),intent);
//            this.present(new DetailAbilitySlice(),intent);
        });

        Component productLayout3 = pageSlider.findComponentById(ResourceTable.Id_layout_product03);
        productLayout3.setClickedListener(component -> {
            //当index==0时，绑定商品列表的点击事件，点击跳转到详情⻚时，将商品id传递过去
            Intent intent = new Intent();
            Text s=(Text) findComponentById(ResourceTable.Id_product_name_text3);
            String s1 = s.getText();

            Text a=(Text) findComponentById(ResourceTable.Id_product_price_text13);
            String a1 = a.getText();

            intent.setParam("aproductId",a1);
            intent.setParam("productId",s1);
            this.present(new DetailAbilitySlice3(),intent);
//            this.present(new DetailAbilitySlice(),intent);
        });

        Component productLayout4 = pageSlider.findComponentById(ResourceTable.Id_layout_product014);
        productLayout4.setClickedListener(component -> {
            //当index==0时，绑定商品列表的点击事件，点击跳转到详情⻚时，将商品id传递过去
            Intent intent = new Intent();
            Text s=(Text) findComponentById(ResourceTable.Id_product_name_text4);
            String s1 = s.getText();

            Text a=(Text) findComponentById(ResourceTable.Id_product_price_text14);
            String a1 = a.getText();

            intent.setParam("aproductId",a1);
            intent.setParam("productId",s1);
            this.present(new DetailAbilitySlice4(),intent);

        });
        //轮播图通知事件

        // 初始化轮播图数据
        getGlobalTaskDispatcher(TaskPriority.DEFAULT).asyncDispatch(() -> {
            List<Integer> imagelist = new ArrayList<>();
            imagelist.add(ResourceTable.Media_img01);
            imagelist.add(ResourceTable.Media_img02);
            imagelist.add(ResourceTable.Media_img04);
            getUITaskDispatcher().asyncDispatch(() -> {
                IndexImgPageSliderProvider provider = new IndexImgPageSliderProvider(imagelist, this);
                indexImgPageSlider = (PageSlider) findComponentById(ResourceTable.Id_index_image_pageslider);
                indexImgPageSlider.setProvider(provider);
                // 启动自动播放
                startAutoSlide(indexImgPageSlider, imagelist.size());
            });

            });


        TableLayout tableLayout = (TableLayout)findComponentById(ResourceTable.Id_id1);
        tableLayout.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                sendPicMsg();
            }
        });


        //监听首页的搜索输入框，点击输入框则跳转到SearchAbilitySlice
        TextField searchTextField = (TextField) findComponentById(ResourceTable.Id_index_search_textfield);
        searchTextField.setFocusChangedListener(this);
    }
    //轮播图的定时事件
    private void startAutoSlide(PageSlider pageSlider, int pageCount) {
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(() -> {
            getUITaskDispatcher().asyncDispatch(() -> {
                if (pageSlider != null && pageCount > 0) {
                    currentPage = (currentPage + 1) % pageCount;
                    pageSlider.setCurrentPage(currentPage);
                }
            });
        }, 2, 2, TimeUnit.SECONDS); // 每2秒切换一次
    }


    @Override
    protected void onInactive() {
        super.onInactive();
        stopAutoSlide(); // 当页面不可见时停止自动播放
    }
    private void stopAutoSlide() {
        if (scheduler != null && !scheduler.isShutdown()) {
            scheduler.shutdown();
        }
    }
    private void sendPicMsg() {
        NotificationSlot slot = new NotificationSlot("slot_002", "pic_slot", NotificationSlot.LEVEL_DEFAULT);
        slot.setDescription("发布图片通知");
        try {
            NotificationHelper.addNotificationSlot(slot);
        } catch (RemoteException e) {
            throw new RuntimeException(e);
        }


        int notificationId = 1002;
        NotificationRequest request = new NotificationRequest(notificationId);
        request.setSlotId(slot.getId());

        NotificationRequest.NotificationPictureContent content = new NotificationRequest.NotificationPictureContent();
        content.setTitle("泡泡玛特上新啦")
                .setText("隐藏盲盒等待你发现！")
                .setExpandedTitle("泡泡玛特")
                .setBigPicture(getPixelMap(ResourceTable.Media_img02));

        NotificationRequest.NotificationContent notificationContent = new NotificationRequest.NotificationContent(content);
        request.setContent(notificationContent);
        try {
            NotificationHelper.publishNotification(request);
        } catch (RemoteException e) {
            throw new RuntimeException(e);
        }

    }

    private PixelMap getPixelMap(int imgId){
        InputStream inputStream =null;
        try{
            inputStream = getContext().getResourceManager().getResource(imgId);
            ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
            ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
            ImageSource imageSource = ImageSource.create(inputStream,sourceOptions);
            decodingOptions.desiredPixelFormat = PixelFormat.ARGB_8888;
            return imageSource.createPixelmap(decodingOptions);
        } catch (NotExistException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    @Override
    public void onActive() {
        super.onActive();
    }


    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public void onFocusChange(Component component, boolean b) {
        if(b){
            present(new SearchAbilitySlice(),new Intent());
        }

    }
}
